/**

 @Name：layuiAdmin iframe版主入口
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
    	
 */

layui.extend({
    setter: 'config', //配置模块
    admin: 'lib/admin', //核心模块
    view: 'lib/view', //视图渲染模块
    navbar: 'modules/navbar', //左侧的菜单
    zlPinYin: 'lib/zlPinYin',
}).define(['setter', 'admin', 'navbar', 'zlPinYin'], function (exports) {
    var setter = layui.setter,
        element = layui.element,
        admin = layui.admin,
        tabsPage = admin.tabsPage,
        view = layui.view,
        zlPinYin = layui.zlPinYin,
        navbar = layui.navbar(),
		message = new Messenger('index', 'kdayunmanager')
        //打开标签页
        openTabsPage = function (url, text, resid) {
            //遍历页签选项卡
            var matchTo, tabs = $('#LAY_app_tabsheader>li'),
                path = url.replace(/(^http(s*):)|(\?[\s\S]*$)/g, '');
            if (url.indexOf('isnewtab=1') > -1) {
                window.open(url, "_blank");
                return;
            }
            tabs.each(function (index) {
                var li = $(this),
                    layid = li.attr('lay-id'),
                    tempresid = resid ? resid : url;
                if (layid === tempresid) {
                    matchTo = true;
                    tabsPage.index = index;
                }
            });

            text = text || '新标签页';

            if (setter.pageTabs) {
                //如果未在选项卡中匹配到，则追加选项卡
                if (!matchTo) {
                    $(APP_BODY).append([
                        '<div class="layadmin-tabsbody-item layui-show">',
                        '<iframe src="' + url + '" frameborder="0" menuid=' + resid + ' class="layadmin-iframe" name="layadmin-iframe"></iframe>',
                        '</div>'
                    ].join(''));
                    tabsPage.index = tabs.length;
                    element.tabAdd(FILTER_TAB_TBAS, {
                        title: '<span>' + text + '</span>',
                        id: resid ? resid : url,
                        attr: path
                    });
                    setPrevAndNext();
                    $('.layadmin-tabsbody-shade').show();
                }
            } else {
                var iframe = admin.tabsBody(admin.tabsPage.index).find('.layadmin-iframe');
                iframe[0].contentWindow.location.href = url;
            }
            var $iframe
            if (path.indexOf('/coremodelshow') != -1 && resid) {
                $iframe = $(APP_BODY).find('iframe[menuid="' + resid + '"]');
            }
            else {
                $iframe = $(APP_BODY).find('iframe[src="' + url + '"]');
            }

            $iframe && !$iframe.attr('loaded') && ($('.layadmin-tabsbody-shade').show()) && $iframe.load(function () {
                $('.layadmin-tabsbody-shade').fadeOut('600');
                $iframe.attr('loaded', 'true')
            });

            //定位当前tabs
            element.tabChange(FILTER_TAB_TBAS, resid ? resid : url);
            admin.tabsBodyChange(tabsPage.index, {
                url: resid ? resid : url,
                text: text
            });
        },
        setPrevAndNext = function () {
            var $li = $('.layui-tab-title').children('li')
                , sumwidth = 0
                , totalwidth = $('.layui-tab-title').width();
            for (var i = 0; i < $li.length; i++) {
                sumwidth = sumwidth + $li.eq(i).outerWidth();
            }
            if (sumwidth > totalwidth) {
                $('.layadmin-pagetabs').css({ "padding-left": "40px", "padding-right": "80px" });
                $('.layui-icon-prev').show();
                $('.layui-icon-next').show();
            } else {
                $('.layadmin-pagetabs').css({ "padding-left": "0px", "padding-right": "40px" });
                $('.layui-icon-prev').hide();
                $('.layui-icon-next').hide();
            }
        },
        /**
        * 开启layer的页面
        */
        openLayerPage = function (pageCoinfg,params) {
	        var pageId = params.__pageId;
            //页面创建加载完成
            pageId && message.on(pageId, 'onPageLoad', function (msg) {
				let iframes = top.window.document.getElementsByTagName("iframe"); 
				for(var i=0;i<iframes.length;i++){
					var iframe=iframes[i];
					if(iframe.contentWindow.location.href.indexOf('='+pageId)!=-1){
						message.sendMessage(pageId, 'onSuccess')
						break;		
					}
				}
            })
            var p = $.extend(pageCoinfg, {
                type: 2,
                area: pageCoinfg.area || ['420px', '240px'],
				success: () => {
                }
                , yes: () => {
                    pageId && message.sendMessage(pageId, 'onYes')
                }
                , no: () => {
                    pageId && message.sendMessage(pageId, 'onCancel')
                }
				, end: () => {
                    pageId && message.sendMessage(pageId, 'onEnd')
                }
                , onCanClose: () => {
                   return pageId && message.sendMessage(pageId, 'onCanClose')
				}
                , onClosed: () => {
                    pageId && message.sendMessage(pageId, 'onClosed')
                }, full: () => {
                    pageId && message.sendMessage(pageId, 'onFull')
                }, min: () => {
                    pageId && message.sendMessage(pageId, 'onMin')
                }, resizing: () => {
                    pageId && message.sendMessage(pageId, 'onResizing')
                }, moveEnd: () => {
                    pageId && message.sendMessage(pageId, 'onMoveEnd')
                }, restore: () => {
                    pageId && message.sendMessage(pageId, 'onRestore')
                }
            });
            layer.open(p);
        },
        APP_BODY = '#LAY_app_body',
        FILTER_TAB_TBAS = 'layadmin-layout-tabs',
        $ = layui.$;
    window.addEventListener('message', function (event) {
        if (event.data) {
            let d = JSON.parse(event.data);
            if (d && d.msg == 'openTabPage') {
                openTabsPage(d.params.url, d.params.title, d.params.resid);
            }
            if (d && d.msg == 'openTopPage') {
                openLayerPage(d.params.pageCoinfg, d.params.param);
            }
        }
    });

    //将模块根路径设置为 controller 目录
    layui.config({
        base: setter.base + 'modules/'
    });

    //扩展 lib 目录下的其它模块
    layui.each(setter.extend, function (index, item) {
        var mods = {};
        mods[item] = '{/}' + setter.base + 'lib/extend/' + item;
        layui.extend(mods);
    });

    view().autoRender();


    //设置navbar
    navbar.set({
        spreadOne: true,
        elem: '#admin-navbar-side',
        cached: false,
        // data: navs,
        url: layui.cache['contentPath'] + '/core/security/querymenuauth',
        type: 'post'
        /*cached:true,
        url: 'datas/nav.json'*/
    });
    //渲染navbar
    navbar.render();

    //加载公共模块
    layui.use('common');

    //获取当前用户信息并填充
    $.ajax({
        url: layui.cache['contentPath'] + '/admin/coreuser/querycuruserinfo',
        type: 'post',
        async: false,
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            var data = result.obj;
            if (!data) {
                return;
            }
            $('#OBJNAME').html(data.userCursor.OBJNAME);
            $('#ORGNAME').html(data.currentOrgName);
            if (data.currentDeptName == '') {
                $('#ROLENAME').html(data.currentRoleName);
            } else {
                $('#ROLENAME').html(data.currentDeptName + '-' + data.currentRoleName);
            }

            $('#ROLENAME').attr('roleid', data.currentRoleId);
            $('#ROLENAME').attr('deptid', data.currentDeptId);
            if (data.userCursor.TOUX != undefined && data.userCursor.TOUX != null && data.userCursor.TOUX != '') {
                $('#TOUX').prop('src', layui.cache['contentPath'] + data.userCursor.TOUX);
            } else {
                $('#TOUX').prop('src', layui.cache['contentPath'] + '/static/image/userImg.png');
            }
            var rolelist = data.roleCursor;
            var html = '',
                $rolecourse = $('#rolecourse');
            for (var i = 0; i < rolelist.length; i++) {
                html += '<dd>';
                if (rolelist[i].DEPTNAME != "") {
                    html += '  <a style="cursor:pointer" name="roleswitch" deptid="' + rolelist[i].DEPTID + '" roleid="' + rolelist[i].ROLEID + '">';
                    html += rolelist[i].DEPTNAME + '-' + rolelist[i].ROLENAME;
                } else {
                    html += '  <a name="roleswitch" roleid="' + rolelist[i].ROLEID + '">';
                    html += rolelist[i].ROLENAME;
                }
                html += '   </a>';
                html += '</dd>';
            }
            $rolecourse.append(html);
            addclickevent();
            //查询前台页面系统选项
            $.ajax({
                url: layui.cache['contentPath'] + '/manager/coresysopt/querybyid',
                type: 'post',
                async: true,
                data: { 'orgid': data.currentOrgId, 'optid': '2F6E174513EE460A971CCD641EC77198' },
                dataType: 'json',
                success: function (setdata) {
                    setdata = setdata.obj;
                    if (setdata != '') {
                        var dataArray = setdata.split(',');
                        if (dataArray.length == 1 && dataArray[0] == 'zx') {
                            $('#zx').children('hr').hide();
                            $('#zx').show();
                        } else {
                            $.each(dataArray, function (item, v) {
                                $('#' + v).show();
                            });
                        }
                    } else {
                        $('.setli').hide();
                        $('.layui-nav-more').hide();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg('请求异常!');
                },
            });

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.msg('请求异常!');
        },
    });

    function addclickevent() {
        $('#rolecourse a').on('click', function () {
            var curroleid = $('#ROLENAME').attr('roleid'),
                currdeptid = $('#ROLENAME').attr('deptid'),
                switchroleid = $(this).attr('roleid'),
                deptid = $(this).attr('deptid') == undefined ? '' : $(this).attr('deptid'),
                param = {
                    roleid: switchroleid,
                    deptid: deptid
                }
            if (curroleid == switchroleid && currdeptid == deptid) {
                return;
            } else {
                var index = layer.load();
                $.ajax({
                    url: layui.cache['contentPath'] + '/switchRole?t=' + Math.floor(Math.random() * 100),
                    data: param,
                    type: 'get',
                    async: false,
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (result) {
                        if (result.state == 'OK') {
                            layer.close(index);
                            top.location.href = layui.cache['contentPath'] + '/index?tokenId=' + $('#tokenId').val();
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg('请求异常!');
                    },
                });
            }
        });
    }
    layui.event('WM_USERWFG', 'WM_OPENPAGE', null, function (WParam) {
        if (WParam && WParam.url != '' && WParam.text != '') {
            openTabsPage(WParam.url, WParam.text);
        }
    });
    // 获取待办信息
    $.ajax({
        url: layui.cache['contentPath'] + '/manager/coremessage/query',
        type: 'get',
        async: false,
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            var state = result.state;
            if (state == 'OK') {
                var data = result.obj;
                if (data.length == 0) {
                    $('.layui-badge-dot').remove();
                }
            }
        }
    });


    $('#navbarSearchValue').on('keyup', function (e) {
        navbarSeacherHandle($(this).val(), this)
    });
    $('#navbarSearchIcon').on('click', function () {
        navbarSeacherHandle($(this).siblings('input').val(), this)
    });
    $('#about').on('click', function () {
        layer.open({
            type: 2,
            title: "关于我们",
            area: ['600px', '250px'],
            content: layui.cache['contentPath'] + '/about'
        })
    })
    // 点击搜索项 
    $('ul.navbarSearchResult').on('click', 'li', function () {
        var value = $(this).find('cite').html();
        $('ul.navbarSearchResult').removeClass('layui-show').addClass('layui-hide');
        $(this).parent().siblings('input').val('');
        if (!$('#admin-navbar-side').find('a[lay-tips="' + value + '"]').parent().hasClass('layui-nav-itemed')) {
            $('#admin-navbar-side').find('a[lay-tips="' + value + '"]').click();
        }
        // $('#admin-navbar-side').find('a[lay-tips="' + value + '"]').click();
        // $('#admin-navbar-side').find('.layui-nav-itemed').removeClass('layui-nav-itemed');
        // $('#admin-navbar-side').find('a[lay-tips="' + value + '"]').parents('dd').addClass('layui-nav-itemed');
        // $('#admin-navbar-side').find('a[lay-tips="' + value + '"]').parents('li.layui-nav-item').addClass('layui-nav-itemed');
    })

    function navbarSeacherHandle(value, dom) {
        var targetData = $(dom).parent('div.navbar-side-search').siblings('div#admin-navbar-side').find('a'),
            ulItem = $(dom).siblings('ul.navbarSearchResult'),
            num = 0;
        ulItem.html(' ');
        if (value == '') {
            ulItem.addClass('layui-hide').removeClass('layui-show');
            return;
        }
        for (var i = 0; i < targetData.length; i++) {
            // if ($(targetData[i]).find('span.layui-nav-more').length == 0) {
            var matchingTarget = $(targetData[i]).find('cite').html(),
                imgHtml = $(targetData[i]).find('img').length > 0 ? $(targetData[i]).find('img')[0].outerHTML : '<i class="fa fa-file"></i>';

            if (matchingTarget.indexOf(value) != -1 || zlPinYin.A(matchingTarget).toLowerCase().indexOf(value.toLowerCase()) != -1) {
                ulItem.append('<li class="search-result-item">' + imgHtml + '<cite>' + matchingTarget + '</cite></li>');
                num++;
            }
            // }
        }
        ulItem.removeClass('layui-hide').addClass('layui-show');
        if (num == 0) {
            ulItem.append('<li>未查询到对应数据！</li>')
        }
    }

    // $(document).ready(function () {
    //     $('body').addClass('loaded');
    //     $('#loader-wrapper .load_title').remove();
    // });
    //对外输出
    exports('index', {
        openTabsPage: openTabsPage,
        setPrevAndNext: setPrevAndNext
    });
});